const NodeRSA = require("node-rsa");
const prikey = `
-----BEGIN PRIVATE KEY-----
MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEAy+XGxeeBVuHGi1I3
N5FkwnX0W+OHmaQtFp2NrN9VuGywvxP+CJ9Zxd5Z+D1Amiqf0ni4Ez/ZjP4D3hPV
V2skSQIDAQABAkEAp7bqSJFDd0ahPKo01xVWDwpdJFREjqFXoRmZlo/h/56XJOv1
IrbSsDuzKlPTdnZf/m2X/bXp0xoQ0neJGjJ8fQIhAPOq6xVjwA7Q8HHXHTPEvVJb
4o31ED6WvZTj0zERqv2vAiEA1jeTpmN/sfSvbs3Ki/1JEPBuewYYW1hnIzcrgZyC
s4cCIQDfvEC/Eyh2ckNVRD/8GNn9lYEg97RCxAavf8GbfK2U4QIhAMW1CZq5njNa
B0gWuue03ui5Xt5AY956msYPtyGql56lAiBPfMydgNVLhxlvaRCyPQgCIs75mbuU
jY0HAqvTyv7Haw==
-----END PRIVATE KEY-----
`
const pubkey = `
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMvlxsXngVbhxotSNzeRZMJ19Fvjh5mk
LRadjazfVbhssL8T/gifWcXeWfg9QJoqn9J4uBM/2Yz+A94T1VdrJEkCAwEAAQ==
-----END PUBLIC KEY-----
`
/**
 * 生成公私钥
 */
const getKeys = () => {
    var key = new NodeRSA({b: 512});//生成512位秘钥
    var pubkey = key.exportKey('pkcs8-public');//导出公钥
    var prikey = key.exportKey('pkcs8-private');//导出私钥
    console.log('pubkey' ,pubkey);
    console.log('prikey', prikey);
}
/**
 * 解密
 * @param str 
 */
const decrypt = (str: string): string => {
    const dec = new NodeRSA(prikey);
    dec.setOptions({encryptionScheme: 'pkcs1'}); // 因为jsencrypt自身使用的是pkcs1加密方案, nodejs需要修改成pkcs1。
    const decrypted = dec.decrypt(str, 'utf8');
    console.log('解密后: ', decrypted);
    return decrypted;
}
/**
 * 加密字符串
 * @param str 
 */
const encrypt = (str: string): string => {
    const enc = new NodeRSA(pubkey);
    enc.setOptions({encryptionScheme: 'pkcs1'}); // 因为jsencrypt自身使用的是pkcs1加密方案, nodejs需要修改成pkcs1。
    const encrypted = enc.encrypt(str, 'base64');
    console.log('加密后: ', encrypted);
    return encrypted;
}
export {
    getKeys,
    encrypt,
    decrypt
}